<template>
  <Container class="giftsale-list">
    <div class="container-header title title-center" slot="header">赠品促销</div>
    <div class="container-header mt">
      <SearchSale @onSearchData="onSearchData"></SearchSale>
    </div>
    <div class="bg-light mt">
      <Tabs v-model="tab">
        <template slot="extra">
          <template v-if="tab === 'tab1'">
            <Button class="item" type="primary" icon="md-add" @click="onJoinAdd">批量加入</Button>
          </template>
          <template v-if="tab === 'tab2'">
            <Button class="item" type="primary" icon="md-add" @click="onJoinDelete">批量删除</Button>
          </template>
        </template>
        <TabPane label="选择赠品" name="tab1">
          <choicePrevent ref="choicePrevent"></choicePrevent>
        </TabPane>
        <TabPane :label="label1" name="tab2">
          <present ref="prevent"></present>
        </TabPane>
      </Tabs>
    </div>
    <div class="container-footer bg-white" slot="footer">
      <Button size="large" @click="jumpPrevPage">返回</Button>
      <Button type="primary" size="large" class="ml" @click="onJoinPrevent" :loading="loading">保存</Button>
    </div>
  </Container>
</template>
<script>
import SearchSale from "@/views/sales/common/SearchSale";
import choicePrevent from "./list/ChoicePrevent.vue";
import present from "./list/present.vue";
import { setSelectList, setCascaderList, formatDate, getGift } from "./list/GiftsaleList.js";
import { getPuduct } from "@/views/sales/common/TableSaleMethods";
export default {
  components: {
    choicePrevent,
    present,
    SearchSale
  },
  data() {
    return {
      id: this.$route.query.id || '',
      type: this.$route.query.type || '',
      tab: "tab1",
      loading: false,
      formValidate: {
        name: "",
        date: "",
        time: "",
        interest: "",
        gender: ""
      },
      ruleValidate: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        date: [{ required: true, message: "请开始时间", trigger: "blur" }],
        time: [{ required: true, message: "请结束时间", trigger: "blur" }],
        interest: [
          { required: true, message: "请选择活动对象", trigger: "blur" }
        ]
      },
      label1: (h) => {
        return h('div', [
          h('span', '已选赠品'),
          h('Badge',{
            props: {
              count: this.getSaleNum
            }
          })
        ])
      }
    };
  },
  mounted() {
    if(this.id && !this.$store.state.giftSale.GetgiftData.length) this.getData()
  },
  methods: {
    getData() {
      this.$ajaxGet(`/activity/activity_gift_sku_list/${this.id}`).then(data => {
        this.$store.state.giftSale.GetgiftData = (data[0] || []).map(item => {
          return {
            id: item.item[0].productId,
            checked: false,
            buttonChecked: false,
            showChildren: false,
            discount: '',
            reduce: '',
            sale: '',
            limitQuantity: '',
            code: item.productSn,
            salePrice: '',
            reduce: '',
            stock: '',
            isShelf: item.isShelf,
            discount: '',
            title: item.title,
            productSkuList: item.item.map(todo => {
              return {
                id: todo.skuId,
                productId: todo.productId,
                productSn: todo.productSn,
                parentcode: item.productSn,
                checked: false,
                buttonChecked: false,
                showChildren: false,
                discount: '',
                reduce: '',
                sale: '',
                limitQuantity: '',
                quantity: todo.quantity || 0,
                code: todo.skuSn,
                salePrice: todo.productSkuInfo.salePrice,
                reduce: '',
                sale: todo.promotionPrice,
                stock: '',
                isShelf: todo.isShelf,
                discount: '',
                title: '',
                stock: todo.productSkuInfo.stock,
                returnPrice: todo.returnPrice || 0
              }
            })
          }
        })
        this.onSearchData()
      })
    },
    onJoinAdd() {
      this.$refs.choicePrevent.getSaleData('checked');
    },
    onSearchData(param) {
      this.$refs.choicePrevent.getProductData(param);
    },
    jumpPrevPage() {
      this.$router.back();
    },
    onJoinDelete() {
      this.$refs.prevent.deleteSaleData();
    },
    onJoinPrevent() {
      let self = this;
      let status = false;
      if (!(this.productSkuList.length || !this.giftSkuList.length)) {
        self.$Message.error("活动商品和活动赠品必需选择");
        return false;
      }
      for (let item of self.giftSkuList) {
        if (!item.returnPrice || !item.quantity) {
          status = true;
        }
      }
      if (status) {
        self.$Message.error("退货价或者赠品数量必需添加");
        return false;
      }
      if (!this.getSaleNum) {
        self.$Message.error("赠品必选");
        return false
      }
      if (this.getSaleNum> 5) {
        self.$Message.error("赠品数量不能多于5个");
        return false
      }
      self.loading = true;
      let param = {
        activityInfoDTO: {
          activityDescription: this.$store.state.giftSale.Giftsaleform.remarks, //活动备注
          activityName: this.$store.state.giftSale.Giftsaleform.name, //活动名称
          joinTypeEnum: "PART",
          productSkuList: this.productSkuList,
          storeTypeEnumList: this.promotionMemberScope,
          startDate: this.timeList[0].startDatetime,
          endDate: this.timeList[0].endDatetime,
          shelfStatusEnum: 'ON'
        },
        activityGiftDTO: {
          giftTimeList: this.timeList,
          giftProductSkuList: this.giftSkuList,
          minQuantityPerBuy: this.$store.state.giftSale.Giftsaleform.least
        }
      };
      let url = "/activity/gift/save"
      if (this.id && this.type) {
        url = "/activity/gift/edit"
        param.activityGiftDTO.activityId = this.id
      }
      this.$jsonPost(url, param).then(data => {
        self.$Message.success((this.id && this.type) ? '编辑活动成功' : "新增活动成功");
        self.$store.commit('setGiftSaleEmpty')
        self.$router.push({name: 'sales/list'})
        self.loading = false
      }).catch(data => {
        self.loading = false;
      });
    }
  },
  computed: {
    getSaleNum () {
      return this.$store.getters.giftSaleNum
    },
    grade() {
      return this.$store.state.giftSale.Giftsaleform.grade.join(",");
    },
    timeList() {
      return this.$store.getters.giftTimeList;
    },
    productSkuList() {
      return getPuduct(this.$store.state.giftSale.GetsaleData, {
        child: "productSkuList",
        getParam: ["productId", "id", "parentcode", "code"]
      });
    },
    giftSkuList() {
      return getGift(this.$store.state.giftSale.GetgiftData, {
        child: "productSkuList",
        getParam: [
          "productId",
          "id",
          "quantity",
          "returnPrice",
          "parentcode",
          "code"
        ]
      });
    },
    promotionMemberScope() {
      return this.$store.state.giftSale.Giftsaleform.grade;
    }
  }
};
</script>
